'use client'

import { useAuth } from '@/hooks/use-auth'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useState } from 'react'
import { useRouter } from 'next/navigation'

export default function TestPermissionsPage() {
  const [tableName, setTableName] = useState('base_params')
  const [dataSource, setDataSource] = useState('P')
  const { user, permissions, loading, error, canEditField, hasDataSourceAccess, logout } = useAuth(tableName, dataSource)
  const router = useRouter()

  // 测试字段列表
  const testFields = [
    '设备名称', '制造厂家', '供货厂家', '型号', '规格', 
    '额定功率', '额定电流', '额定转速', '装箱单号',
    '设备编号', '设备标签', '功能描述',
    '安装位置', '系统分区', '楼层信息', '采购批次', '供应商信息',
    '出厂日期', '技术参数', '出厂编号', '序列号', '制造批次',
    '运行状态', '维护记录', '运维编号', '当前位置', '运维责任人'
  ]

  const dataSourceOptions = [
    { value: 'P', label: '采购 (P)' },
    { value: 'E', label: '工程 (E)' },
    { value: 'M', label: '制造 (M)' },
    { value: 'O', label: '运维 (O)' }
  ]

  const tableOptions = [
    { value: 'base_params', label: '基础参数' },
    { value: 'naming', label: '命名参数' },
    { value: 'position', label: '位置参数' }
  ]

  const handleLogout = async () => {
    await logout()
    router.push('/login')
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="w-full max-w-md">
          <CardHeader>
            <CardTitle className="text-red-600">认证失败</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-gray-600 mb-4">{error}</p>
            <Button onClick={() => router.push('/login')} className="w-full">
              前往登录
            </Button>
          </CardContent>
        </Card>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 p-4">
      <div className="max-w-6xl mx-auto space-y-6">
        {/* 用户信息 */}
        <Card>
          <CardHeader>
            <div className="flex justify-between items-center">
              <CardTitle>权限测试页面</CardTitle>
              <Button variant="outline" onClick={handleLogout}>
                登出
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            {user && (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <div>
                  <div className="text-sm font-medium text-gray-600">用户名</div>
                  <div className="text-lg font-semibold">{user.full_name}</div>
                  <div className="text-sm text-gray-500">@{user.username}</div>
                </div>
                <div>
                  <div className="text-sm font-medium text-gray-600">角色</div>
                  <Badge variant="default">{user.role_name}</Badge>
                </div>
                <div>
                  <div className="text-sm font-medium text-gray-600">数据来源权限</div>
                  <div className="flex flex-wrap gap-1">
                    {permissions?.dataSourceAccess.map(source => (
                      <Badge key={source} variant="outline" className="text-xs">
                        {source === 'P' && '采购'}
                        {source === 'E' && '工程'}
                        {source === 'M' && '制造'}
                        {source === 'O' && '运维'}
                      </Badge>
                    ))}
                  </div>
                </div>
                <div>
                  <div className="text-sm font-medium text-gray-600">特殊权限</div>
                  <div className="space-y-1">
                    {permissions?.canEditAll && <Badge variant="default" className="text-xs">全部编辑</Badge>}
                    {permissions?.canManageUsers && <Badge variant="secondary" className="text-xs">用户管理</Badge>}
                    {permissions?.canManageRoles && <Badge variant="secondary" className="text-xs">角色管理</Badge>}
                  </div>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 测试控制 */}
        <Card>
          <CardHeader>
            <CardTitle>权限测试控制</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label htmlFor="tableName">表类型</Label>
                <select
                  id="tableName"
                  value={tableName}
                  onChange={(e) => setTableName(e.target.value)}
                  className="w-full mt-1 p-2 border rounded-md"
                >
                  {tableOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <Label htmlFor="dataSource">数据来源</Label>
                <select
                  id="dataSource"
                  value={dataSource}
                  onChange={(e) => setDataSource(e.target.value)}
                  className="w-full mt-1 p-2 border rounded-md"
                >
                  {dataSourceOptions.map(option => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            
            <div className="mt-4">
              <div className="text-sm font-medium text-gray-600 mb-2">
                当前数据来源访问权限: 
                <Badge variant={hasDataSourceAccess(dataSource) ? "default" : "destructive"} className="ml-2">
                  {hasDataSourceAccess(dataSource) ? "有权限" : "无权限"}
                </Badge>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 字段权限测试 */}
        <Card>
          <CardHeader>
            <CardTitle>字段编辑权限测试</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
              {testFields.map((field) => {
                const canEdit = canEditField(field)
                return (
                  <div
                    key={field}
                    className={`p-3 border rounded-lg ${
                      canEdit 
                        ? 'border-green-200 bg-green-50' 
                        : 'border-red-200 bg-red-50'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium">{field}</span>
                      <Badge 
                        variant={canEdit ? "default" : "destructive"}
                        className="text-xs"
                      >
                        {canEdit ? "可编辑" : "只读"}
                      </Badge>
                    </div>
                  </div>
                )
              })}
            </div>
            
            {permissions?.editableFields && permissions.editableFields.length > 0 && (
              <div className="mt-6">
                <div className="text-sm font-medium text-gray-600 mb-2">
                  当前配置的可编辑字段 ({tableName}):
                </div>
                <div className="flex flex-wrap gap-2">
                  {permissions.editableFields.map(field => (
                    <Badge key={field} variant="outline">
                      {field}
                    </Badge>
                  ))}
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* 导航链接 */}
        <Card>
          <CardHeader>
            <CardTitle>系统导航</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="flex flex-wrap gap-4">
              <Button variant="outline" onClick={() => router.push('/')}>
                返回首页
              </Button>
              {permissions?.canManageUsers && (
                <Button variant="outline" onClick={() => router.push('/admin')}>
                  管理后台
                </Button>
              )}
              <Button variant="outline" onClick={() => router.push('/piping')}>
                配管专业
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
